package org.bozo.im.service.protocols.jabber;

import java.util.Collection;

import org.bozo.im.common.types.RawContact;
import org.bozo.im.common.types.RawContact.Field;
import org.bozo.im.service.IMService;
import org.bozo.im.service.IMSessionConfiguration;
import org.bozo.im.service.core.roster.IMRoster;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.packet.Presence;

public class JabberRosterListener implements RosterListener {

	private IMSessionConfiguration mConfiguration;
	private IMRoster mIMRoster;
	private Roster mRoster;

	public JabberRosterListener(IMSessionConfiguration pConfiguration, Roster pRoster) {
		mConfiguration = pConfiguration;
		mRoster = pRoster;
		mRoster.addRosterListener(this);
		
		mIMRoster = IMService.getInstance().getRoster();
	}

	public void entriesAdded(Collection<String> pAddresses) {
		
		for (String lAddress : pAddresses) {
			RosterEntry lEntry = mRoster.getEntry(lAddress);
			mIMRoster.addContact(mConfiguration.getProtocol(), lEntry.getUser(), lEntry.getName());
		}
		
		mIMRoster.pushContacts();
		
		IMService.getInstance().updateRoster();
	}

	public void entriesDeleted(Collection<String> pAddresses) {
		// TODO Auto-generated method stub

	}

	public void entriesUpdated(Collection<String> pAddresses) {
		// TODO Auto-generated method stub

	}

	public void presenceChanged(Presence pPresence) {
		RawContact lContact = mIMRoster.getContact(mConfiguration.getProtocol(), pPresence.getFrom());
		lContact.setPresence(JabberUtils.convert(pPresence));
		
		mIMRoster.itemModified(lContact, Field.PRESENCE);
		IMService.getInstance().updateRoster();
	}

}
